package vip.liux.front.infrastructure.aop.interceptor;

import vip.liux.front.domain.enums.EntityChangeType;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

public class EntityChangeInfo implements Serializable {
    /**
     * 数据更改时间。
     */
    private LocalDateTime changeTime;

    /**
     * 数据更改类型。
     */
    private EntityChangeType changeType;

    /**
     * 相关实体的 TenantId。
     * 这不是审核日志条目的 TenantId。
     * 单个审核日志条目中可以有多个租户数据更改。
     */
    private Long entityTenantId;

    /**
     * 实体Id。
     */
    private String entityId;

    /**
     * 实体类型全名。
     */
    private String entityTypeFullName;

    /**
     * 属性更改信息。
     */
    private List<EntityPropertyChangeInfo> propertyChanges;


    private Object entityEntry;

    public void merge(EntityChangeInfo changeInfo) {
        for (var propertyChange : changeInfo.getPropertyChanges()) {

            Optional<EntityPropertyChangeInfo> existingChange = this.propertyChanges.stream().filter(p -> Objects.equals(propertyChange.getPropertyName(), p.getPropertyName())).findFirst();

            if (existingChange.isEmpty()) {
                this.propertyChanges.add(propertyChange);
            } else {
                existingChange.get().setNewValue(propertyChange.getNewValue());
            }
        }
    }

    public LocalDateTime getChangeTime() {
        return changeTime;
    }

    public void setChangeTime(LocalDateTime changeTime) {
        this.changeTime = changeTime;
    }

    public EntityChangeType getChangeType() {
        return changeType;
    }

    public void setChangeType(EntityChangeType changeType) {
        this.changeType = changeType;
    }

    public Optional<Long> getEntityTenantId() {
        return Optional.ofNullable(this.entityTenantId);
    }

    public void setEntityTenantId(Long entityTenantId) {
        this.entityTenantId = entityTenantId;
    }

    public String getEntityId() {
        return entityId;
    }

    public void setEntityId(String entityId) {
        this.entityId = entityId;
    }

    public String getEntityTypeFullName() {
        return entityTypeFullName;
    }

    public void setEntityTypeFullName(String entityTypeFullName) {
        this.entityTypeFullName = entityTypeFullName;
    }

    public List<EntityPropertyChangeInfo> getPropertyChanges() {
        return propertyChanges;
    }

    public void setPropertyChanges(List<EntityPropertyChangeInfo> propertyChanges) {
        this.propertyChanges = propertyChanges;
    }

    public Object getEntityEntry() {
        return entityEntry;
    }

    public void setEntityEntry(Object entityEntry) {
        this.entityEntry = entityEntry;
    }
}
